package com.walker.kuyun.viewmodel

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.walker.kuyun.App
import com.walker.kuyun.R
import com.walker.kuyun.bean.*
import com.walker.kuyun.config.Api
import com.walker.kuyun.config.Const
import com.walker.kuyun.database.getAppDataBase
import com.walker.kuyun.util.JsoupUtil
import com.walker.kuyun.util.ParseHtmlUtil.parseLpic
import com.walker.kuyun.util.ParseHtmlUtil.parseNextPages
import com.walker.kuyun.util.Util.showToastOnThread
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.jsoup.select.Elements
import java.net.URLEncoder


class SearchViewModel : ViewModel() {
    var searchResultList: MutableList<VideoCoverBean> = ArrayList()
    var mldSearchResultList: MutableLiveData<Int> = MutableLiveData()   // value：-1错误；0重新获取；1刷新
    var keyWord = ""
    var mldFailed: MutableLiveData<Boolean> = MutableLiveData()
    var searchHistoryList: MutableList<SearchHistoryBean> = ArrayList()
    var mldSearchHistoryList: MutableLiveData<Boolean> = MutableLiveData()
    var mldInsertCompleted: MutableLiveData<Boolean> = MutableLiveData()
    var mldUpdateCompleted: MutableLiveData<Int> = MutableLiveData()
    var mldDeleteCompleted: MutableLiveData<Int> = MutableLiveData()
    var pageNumberBean: PageNumberBean? = null
    var newPageIndex: Pair<Int, Int>? = null

    fun getSearchData(keyWord: String, isRefresh: Boolean = true, partUrl: String = "") {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val url = Api.MAIN_URL + "/vod/search.html?wd=" + URLEncoder.encode(
                    keyWord,
                    "utf-8"
                )
                val document = JsoupUtil.getDocument(url)
                val searchList =
                    document.getElementsByClass("fed-deta-info fed-deta-padding fed-line-top fed-margin fed-part-rows fed-part-over")

                val videoCover3List: MutableList<VideoCoverBean> = java.util.ArrayList()
                for (element in searchList) {
                    // <dt class="fed-deta-images fed-list-info fed-col-xs3">
                    //      <a class="fed-list-pics fed-lazy fed-part-2by3" href="/vod/detail/id/72166.html" data-original="/upload/vod/20201106-1/28d7401c79812706e307ff75c5b39910.jpg">
                    //        <span class="fed-list-play fed-hide-xs"></span>
                    //        <span class="fed-list-score fed-font-xii fed-back-green">9.0</span>
                    //        <span class="fed-list-remarks fed-font-xii fed-text-white fed-text-center">更新至</span>
                    //      </a>
                    // </dt>
                    val img = element.select("dt a.fed-list-pics.fed-lazy.fed-part-2by3")
                        .attr("data-original")
                    val href =
                        element.select("dt a.fed-list-pics.fed-lazy.fed-part-2by3").attr("href")
                    val title = element.select("h1.fed-part-eone.fed-font-xvi a").text()
                    val score =
                        element.select("dt a.fed-list-pics.fed-lazy.fed-part-2by3 span.fed-list-score.fed-font-xii.fed-back-green")
                            .text()
                    val epoiseInfo =
                        element.select("dt a.fed-list-pics.fed-lazy.fed-part-2by3 span.fed-list-remarks.fed-font-xii.fed-text-white.fed-text-center")
                            .text()
                    val listInfo = element.select("ul.fed-part-rows li")
                    //dt a.fed-list-pics.fed-lazy.fed-part-2by3   data-original/href
                    //h1.fed-part-eone.fed-font-xvi a             title
                    //dt a.fed-list-pics.fed-lazy.fed-part-2by3 span.fed-list-score.fed-font-xii.fed-back-green    score
                    //dt a.fed-list-pics.fed-lazy.fed-part-2by3 span.fed-list-remarks.fed-font-xii.fed-text-white.fed-text-center     epoise
                    //ul.fed-part-rows li    0/actor 1/director 2/kind 3/area 4/year 5/update 6/desc

                    videoCover3List.add(
                        VideoCoverBean(
                            Const.ViewHolderTypeString.ITEM_COVER_3,
                            href,
                            Api.MAIN_URL + href,
                            title,
                            ImageBean("", "", Api.MAIN_URL + img, ""),
                            epoiseInfo, null,
                            listInfo[6].text(),
                            area = VideoAreaBean("", "", "", listInfo[3].text()),
                            date = listInfo[5].text(),
                            score = score.toFloat()
                        )
                    )
                }
                Log.d("TestSearch", "getSearchData: \n$videoCover3List\n\n")
                if (isRefresh) searchResultList.clear()
                searchResultList.addAll(videoCover3List)
                this@SearchViewModel.keyWord = keyWord
                newPageIndex = Pair(0, searchResultList.size)
                mldSearchResultList.postValue(if (isRefresh) 0 else 1)
                if (true) return@launch
//                for (i in searchList.indices) {
//                    val cover = results[i].select("a")
//                        .select("img").attr("src")
//                    val title = results[i].select("h2")
//                        .select("a").attr("title")
//                    val url = results[i].select("h2")
//                        .select("a").attr("href")
//                    val episode = results[i].select("span")
//                        .select("font").text()
//                    val types = results[i].select("span")[1].select("a")
//                    val animeType: MutableList<AnimeTypeBean> = java.util.ArrayList()
//                    for (j in types.indices) {
//                        animeType.add(
//                            AnimeTypeBean(
//                                Const.ViewHolderTypeString.ANIME_COVER_3, types[j].attr("href"),
//                                Api.MAIN_URL + types[j].attr("href"),
//                                types[j].text()
//                            )
//                        )
//                    }
//                    val describe = results[i].select("p").text()
//                    animeCover3List.add(
//                        AnimeCoverBean(
//                            Const.ViewHolderTypeString.ANIME_COVER_3,
//                            url,
//                            Api.MAIN_URL + url,
//                            title,
//                            ImageBean("", "", cover, ""),
//                            episode,
//                            animeType,
//                            describe
//                        )
//                    )
//                }
//                return animeCover3List


                val lpic: Elements = document.getElementsByClass("area")
                    .select("[class=fire l]").select("[class=lpic]")
                pageNumberBean = null
                if (isRefresh) searchResultList.clear()
                val positionStart = searchResultList.size
                searchResultList.addAll(parseLpic(lpic[0], url))

                val pages = lpic[0].select("[class=pages]")
                if (pages.size > 0) pageNumberBean = parseNextPages(pages[0])

                this@SearchViewModel.keyWord = keyWord
                newPageIndex = Pair(positionStart, searchResultList.size)
                mldSearchResultList.postValue(if (isRefresh) 0 else 1)
            } catch (e: Exception) {
                mldFailed.postValue(true)
                e.printStackTrace()
                (App.getApp()
                    .getString(R.string.get_data_failed) + "\n" + e.message).showToastOnThread()
            }
        }
    }

    fun getSearchHistoryData() {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                searchHistoryList.clear()
                searchHistoryList.addAll(getAppDataBase().searchHistoryDao().getSearchHistoryList())
            } catch (e: Exception) {
                e.printStackTrace()
                (App.getApp()
                    .getString(R.string.get_data_failed) + "\n" + e.message).showToastOnThread()
            } finally {
                mldSearchHistoryList.postValue(true)
            }
        }
    }

    fun insertSearchHistory(searchHistoryBean: SearchHistoryBean) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val index = searchHistoryList.indexOf(searchHistoryBean)
                if (index != -1) {
                    searchHistoryList.removeAt(index)
                    searchHistoryList.add(0, searchHistoryBean)
                    getAppDataBase().searchHistoryDao().deleteSearchHistory(searchHistoryBean.title)
                    getAppDataBase().searchHistoryDao().insertSearchHistory(searchHistoryBean)
                } else {
                    searchHistoryList.add(0, searchHistoryBean)
                    getAppDataBase().searchHistoryDao().insertSearchHistory(searchHistoryBean)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                mldInsertCompleted.postValue(true)
            }
        }
    }

    fun updateSearchHistory(searchHistoryBean: SearchHistoryBean, itemPosition: Int) {
        GlobalScope.launch(Dispatchers.IO) {
            try {
                searchHistoryList[itemPosition] = searchHistoryBean
                getAppDataBase().searchHistoryDao().updateSearchHistory(searchHistoryBean)
            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                mldUpdateCompleted.postValue(itemPosition)
            }
        }
    }

    fun deleteSearchHistory(itemPosition: Int) {
        GlobalScope.launch(Dispatchers.IO) {
            try {
                val searchHistoryBean = searchHistoryList.removeAt(itemPosition)
                getAppDataBase().searchHistoryDao().deleteSearchHistory(searchHistoryBean.timeStamp)
            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                mldDeleteCompleted.postValue(itemPosition)
            }
        }
    }

    companion object {
        const val TAG = "SearchViewModel"
    }
}